<?php

namespace addons\shopro\model;

use addons\shopro\exception\Exception;
use think\Model;
use think\Db;

/**
 * 高级礼包
 */
class Gift extends Model
{
    // 表名,不含前缀
    protected $name = 'retail_gift';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    protected $hidden = [];

    // 获取数据列表
    public static function getActivityGift($type)
    {
        if($type){
            $info = self::alias("a")
                ->field('a.id,a.type,a.title,a.subtitle,a.original_price,a.price,a.show_sales,i.image,i.params,i.dispatch_type,i.subtitle,a.weigh,a.live_count')
                ->join('shopro_goods i', 'a.goods_id = i.id')
                //想要的字段
                ->where('a.status','up')
                ->where('a.type',$type)
                ->where('a.deletetime','null')
                ->order('a.weigh','desc')
                ->paginate(10);
        }else{
            $info = self::alias("a")
                ->field('a.id,a.type,a.title,a.subtitle,a.original_price,a.price,a.show_sales,i.image,i.params,i.dispatch_type,i.subtitle,a.weigh,a.live_count')
                ->join('shopro_goods i', 'a.goods_id = i.id')
                //想要的字段
                ->where('a.status','up')
                ->where('a.deletetime','null')
                ->order('a.weigh','desc')
                ->paginate(10);
        }

        //$info = collection($info)->toArray();
        $info = $info->items();
        foreach ($info as $key => &$value) {
            $value['image'] = self::geturl($value['image']);
        }
        // $little_gaojilibao = self::getActivityGivegift($user_id,'gift');
        // $res = array_merge($info,$little_gaojilibao);
        return $info;
    }

    // 获取礼包详情列表
    public static function getActivityGiftDetail($ids,$is_big)
    {   
        if($is_big == '1'){
            $info = db('retail_gift')
            ->field('id,type,title,subtitle,original_price,price,show_sales,goods_id')
            ->where('id',$ids)
            ->find();
        }else{
            $info = db('retail_gift_give')
            ->field('id,type,title,subtitle,original_price,price,show_sales,goods_id,salestatus')
            ->where('id',$ids)
            ->find();
        }
        $info  = collection($info)->toArray();
        if($is_big =='1'){
            $user = User::info();
            $uid = $user->id;
            $res = db('retail_user')->where('uid',$uid)->find();
            if($res){
                $info['level'] = $res['level'];
            }else{
                $info['level'] = '0';
            }
        }else{
            $info['type'] = 'l'.$info['type'];
        } 
        $detail = \addons\shopro\model\Goods::getGoodsDetail($info['goods_id']);


        $sku_price = $detail['sku_price'];      // 处理过的规格
        // tp bug json_encode 或者 toArray 的时候 sku_price 会重新查询数据库，导致被处理过的规格又还原回去了
        $detail = json_decode(json_encode($detail), true);
        $detail['sku_price'] = $sku_price;
        $info = array_merge($detail,$info);
        return $info;
    }

    // 获取赠送小礼包列表
    public static function getActivityGivegift($ids,$type)
    {  
        $user_id = $ids;
        $have_gift = db('retail_userbuy_gift')->field('buy_time,receive_num')->where('user_id',$user_id)->where('type',$type)->find();
        $time = time();
        //获取小礼包列表
        $info = db('retail_gift_give')
                ->alias("a")
                ->field('a.id,a.type,a.title,a.subtitle,a.original_price,a.price,a.show_sales,i.image,i.params,i.content,i.dispatch_type,a.weigh,a.salestatus')
                ->join('shopro_goods i', 'a.goods_id = i.id')
                ->where('a.type',$type)
                ->where('a.status','up')
                ->order('a.salestatus','asc')
                ->order('a.weigh','desc')
                ->select();

        if($have_gift){
            //是否在有效时间内的权益
            $live = $have_gift['buy_time'] - $time;
            if($live){
                foreach ($info as $key => &$value) {
                    $value['has'] = 1;
                    $value['receive_num'] = $have_gift['receive_num'];
                    $value['image']   = self::geturl($value['image']);
                }
            }
        }else{
            foreach ($info as $key => &$value) {
                $value['has'] = -1;
                $value['receive_num'] = 0;
                $value['image']   = self::geturl($value['image']);
            }
        }
        return $info;
    }


    /**
     * 玩家报名乡村游
     */
    public static function insTravel($info){
        $res = db('retail_userdraw_gift')
                ->insert($info);
        if($res){
            return true;
        }
        return false;
    }

    /**
     * 额外处理url路径问题
     */
    public static function getContent($content)
    {
        $content = str_replace("<img src=\"/uploads", "<img style=\"width: 100%;!important\" src=\"" . request()->domain() . "/uploads", $content);
        $content = str_replace("<video src=\"/uploads", "<video style=\"width: 100%;!important\" src=\"" . request()->domain() . "/uploads", $content);
        return $content;

    }
    
    /**
     * 处理图片路径问题
     */
    public static function geturl($value)
    {
        if($value){
            return request()->domain() .$value;
        }
    }

    /**
     * 获取玩家活动订单列表
     */

    public static function getOrderlist($type,$user_id){
        $data = db('retail_userbuy_giftlog')
                ->alias("a")
                ->field('i.*,c.*')
                ->where('a.type',$type)
                ->where('a.user_id',$user_id)
                ->join('shopro_order i', 'a.user_id = i.user_id and a.order_id = i.id')
                ->join('shopro_order_item c', 'a.user_id = c.user_id and a.order_id = c.order_id')
                ->select();
        return $data;
    }
    

    /**
     * 获取玩家已经旅游次数
     */
    public static function getTravelLog($type){
        $user = User::info();
        $uid  = $user->id;
        $travel_num = db('retail_userdraw_gift')
                     ->where('user_id',$uid)
                     ->where('type',$type)
                     ->where('status','1')
                     ->select();
        $travel_num = count($travel_num);
        $receive_num =  db('retail_userbuy_gift')
                        ->field('receive_num')
                        ->where('user_id',$uid)
                        ->where('type',$type)
                        ->find();
        if($receive_num['receive_num']){
            $receive_num = $receive_num['receive_num'];
        }else{
            $receive_num = 0;
        }
        return array($travel_num,$receive_num);
    }


    // 团详情
    public static function getActivityGrouponDetail ($id) {
        $activityGroupon = self::with(['my', 'grouponLog'])
                            ->where('id', $id)
                            ->find();

        if (!$activityGroupon) {
            throw new Exception('团未找到');
        }

        $detail = Goods::getGoodsDetail($activityGroupon['goods_id']);
        $activityGroupon['goods'] = $detail;

        // 如果没有关联出来活动，说明活动已结束，这时候处理 显示的活动价
        if ($activityGroupon['goods'] && !$activityGroupon['goods']['activity']) {
                // 活动已结束，或已删除，查询出来
            $activity = \addons\shopro\model\Activity::withTrashed()
                            ->with('activityGoodsSkuPrice')
                            ->where('id', $activityGroupon['activity_id'])->find();

            if ($activity) {
                $currentGoodsActivitySkuPrices = [];
                foreach ($activity['activityGoodsSkuPrice'] as $k => $skuPrice) {
                    if ($skuPrice['status'] == 'up' && $skuPrice['goods_id'] == $activityGroupon['goods_id']) {
                        $currentGoodsActivitySkuPrices[] = $skuPrice;
                    }
                }

                // 当时参加活动真实销量
                $activityGroupon['goods']['sales'] = array_sum(array_column($currentGoodsActivitySkuPrices, 'sales'));
                // 这个是活动最低价
                $activityGroupon['goods']['groupon_price'] = $activityGroupon['goods']['price'] = min(array_column($currentGoodsActivitySkuPrices, 'price'));
            }
        }

        return $activityGroupon;
    }



    public function activity() 
    {
        return $this->belongsTo(\addons\shopro\model\Activity::class, 'activity_id', 'id');
    }


    public function grouponLog()
    {
        return $this->hasMany(\addons\shopro\model\ActivityGrouponLog::class, 'groupon_id', 'id');
    }

    public function leader() {
        return $this->hasOne(\addons\shopro\model\ActivityGrouponLog::class, 'groupon_id', 'id')->where('is_leader', 1);
    }

    public function my() {
        $user = User::info();
        return $this->hasOne(\addons\shopro\model\ActivityGrouponLog::class, 'groupon_id', 'id')->where('user_id', ($user ? $user->id : 0));
    }

    public function goods()
    {
        return $this->belongsTo(\addons\shopro\model\Goods::class, 'goods_id', 'id');
    }
}
